/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.setup.trac.pojo;

import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.IncrementGenerator;
import org.hibernate.type.Type;

/**
 *
 * @author edoardo
 */
public class TracIncrementGenerator extends IncrementGenerator {

    private String sql;
    private Logger log = Logger.getLogger("tracsetup");

    @Override
    public void configure(Type type, Properties params, Dialect dialect) {
        log.debug(dialect);
        Enumeration<?> propertyNames = params.propertyNames();
        log.debug("---------------------------------------------------");
        while (propertyNames.hasMoreElements()) {
            Object object = propertyNames.nextElement();
            log.debug(object + " --> " + params.getProperty((String) object));
        }
        log.debug("---------------------------------------------------");
        log.debug(dialect.getQuerySequencesString());
        String seq = dialect.getSelectSequenceNextValString(params.getProperty("sequence_name"));
        sql = new StringBuffer("select ").append(seq).append(" from dual").toString();

    }

    @Override
    public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
        Serializable result = new BigDecimal(0);
        PreparedStatement pstmt=null;
        ResultSet rs =null;
        try {
            pstmt = session.getBatcher().prepareStatement(sql);
            rs = pstmt.executeQuery();
            rs.next();
            result = new BigDecimal(rs.getString(1));
        } catch (SQLException ex) {
            log.error(ex.getMessage(),ex);
        }
        finally{
            try {
                rs.close();
            } catch (SQLException ex) {
                log.error(ex.getMessage(),ex);
            }
            try {
                session.getBatcher().closeStatement(pstmt);
            } catch (SQLException ex) {
                log.error(ex.getMessage(),ex);
            }
        }
        return result;
    }
}
